package com.example.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.system.entity.Care;
import com.example.system.exception.CustomException;
import com.example.system.mapper.CareMapper;
import com.example.system.service.ICareService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CareServiceImpl extends ServiceImpl<CareMapper, Care> implements ICareService {
    @Autowired
    CareMapper careMapper;

    public int deleteCareByCareId(Integer careId) {
        return careMapper.deleteCareByCareId(careId);
    }

    public void addCareByCare(Care care) {
        //类型一定要有不能为空
        if (care.getType() == null || care.getType().isEmpty()) {
            throw new CustomException("类型不能为空");
        }
        //初始化分数、评价、完成状态为空或0
        if (care.getScore() != null && care.getScore() != 0) {
            care.setScore(0);
        }
        if (care.getAppraise() != null && !care.getAppraise().isEmpty()) {
            care.setAppraise(null);
        }
        if (care.getFinish() != null && care.getFinish() != 0) {
            care.setFinish(0);
        }
        careMapper.addCareByCare(care);
    }

    public void updateCareByCare(Care care) {
        if (care == null) {
            throw new IllegalArgumentException("Care 对象不能为空");
        }
        Care usedCare = careMapper.findCareByCareID(care.getCareId());
        if (usedCare == null) {
            throw new CustomException("未找到对应的 Care 条目");
        }
        if (!care.getUserId().equals(usedCare.getUserId())) {
            throw new CustomException("当前请求修改的用户与原用户的用户名不同");
        }
        if (care.getFinish() == 0)
        {
            if (!care.getScore().equals(usedCare.getScore())) {
                throw new CustomException("护理未完成，不允许更改分数");
            }
            if (!care.getAppraise().equals(usedCare.getAppraise())) {
                throw new CustomException("护理未完成，不允许更改评价");
            }
        }
        careMapper.updateCareByCareId(care.getCareId());
    }


    public Care findCareByCareID(Integer id) {
        return careMapper.findCareByCareID(id);
    }

    public List<Care> findCareByUserID(Integer userId) {
        return careMapper.findCareByUserId(userId);
    }
}
